<?php
/**
 * 财务收款 金额修复
 * @author angl
 */

date_default_timezone_set("Asia/Shanghai");
set_time_limit(0);
if (isset($_SERVER['REQUEST_URI'])) {
    die('error');
}

if (!defined('API_ROOT_PATH')) {
    define('API_ROOT_PATH', dirname(__FILE__));
}

require(API_ROOT_PATH . '/../inc/common.php');
require(API_ROOT_PATH . '/../inc/Config.php');
require(API_ROOT_PATH . '/../inc/MysqliDb.php');

//初始化数据库链接
function init_db()
{
    $db = new MysqliDb ([
        'host' => MYSQLDB,
        'username' => MYSQLDB_USER,
        'password' => MYSQLDB_PWD,
        'db' => MYSQLDB_DATABASE,
        'port' => 3306,
        'prefix' => 'au_',
        'charset' => 'utf8'
    ]);
    return $db;
}

//初始化redis
function init_redis()
{
    $redis = new Redis();
    $redis->connect(REDIS_HOST, REDIS_PORT);
    return $redis;
}

$db = init_db();
$list = $db->get('proceeds_log');

foreach($list as $kl=>$vl){
    $order_id = $vl['order_id'];
    $order = $db->where('order_id',$order_id)->getOne('order','dealer_pay_status,success_price,commision,transfer_type,transfer_fee,coupon');
    if($order['dealer_pay_status']<2){
        continue;
    }
    //过户费
    $order['transfer_fee'] = $order['transfer_type'] == 1 ? 0 : $order['transfer_fee'];
    //代金券
    $coupon_money = 0;
    if ($order['coupon'] > 0) {
        //$coupon_money = M("coupon_log")->where(['order_id' => $order_id, 'occur_type' => 1])->sum('occur_money');
        $coupon_money = $db->where('order_id',$order_id)->where('occur_type',1)->getValue('coupon_log','sum(occur_money)');
        $coupon_money = $coupon_money > $order['coupon'] ? $order['coupon'] : $coupon_money;
    }
    $db->join("activity a",'c.a_id=a.aid','LEFT');
    $raf = $db->where('c.order_id',$vl['order_id'])->where('c.state',1)->where('a.type',1)->getOne("scratch_card c", "c.price");
    $raffle_money = $raf['price'];
    $sum_money = sprintf("%.2f", $order['success_price'] + $order['commision'] + $order['transfer_fee'] - $coupon_money - $raffle_money);
    $db->where('pl_id',$vl['pl_id'])->update('proceeds_log',['amount'=>$sum_money]);
    logUtil($order_id.'-'.$sum_money."元",'INFO');
}
logUtil("数据处理完成","INFO");
